package es.unex.meigas.ww.core;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.FileDataStoreFactorySpi;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import es.unex.sextante.ww.core.PostProcessStrategy;

public class ShapefilePostStrategy implements PostProcessStrategy {

	private String m_sFilename;

	public ShapefilePostStrategy(String filename) {
		this.m_sFilename = filename;
	}
	public void postProcess(FeatureSource<SimpleFeatureType, SimpleFeature> source) {

		if (source != null) {
			FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = null;
			FeatureStore<SimpleFeatureType, SimpleFeature> featureStore = null;
			try {
				SimpleFeatureType ft = source.getSchema();

				File file = new File(m_sFilename);
				Map<String, Serializable> params = new HashMap<String, Serializable>();
				params.put(ShapefileDataStoreFactory.URLP.key, file.toURI()
						.toURL());
				params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key,
						false);

				FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
				ShapefileDataStore dataStore = (ShapefileDataStore) factory
						.createNewDataStore(params);
				dataStore.createSchema(ft);
				featureStore = (FeatureStore<SimpleFeatureType, SimpleFeature>) dataStore.getFeatureSource();
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}

			try {
				// no transaction for shapefile so it doesn't copy all features
				// into memory for the transaction. Just write
				// directly to disk.
				FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
				featureStore.addFeatures(collection);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
